'use strict';

const Controller = require('egg').Controller;
class UserController extends Controller {
  async register() {
    const { ctx, app } = this;
    const user = ctx.request.body;
    const result = await ctx.service.user.create(user);
    ctx.body = { data: result, message: '注册成功', status: 'ok' };
    ctx.status = 200;
  }

  async login() {
    const { ctx, app } = this;
    const username = ctx.request.body.username;
    const password = ctx.request.body.password;
    const result = await ctx.service.user.password(username);
    if (result === password) {
      const user = await ctx.service.user.findByUsername(username)
      const data = { role: 'suadmin' }
      ctx.body = { data: { user: user, token: ctx.helper.createToken(data) }, message: '登陆成功', status: 'ok' };
    } else {
      ctx.body = { message: '登陆失败', status: 'error' };
    }
    ctx.status = 200;
  }

  async getUser() {
    const { ctx, app } = this;
    const users = await ctx.service.user.findAll();
    ctx.body = { data: users };
    ctx.status = 200;
  }

  async createUser() {
    const { ctx, app } = this;
    const name = ctx.request.body.name;
    const result = await ctx.service.user.create(name);
    ctx.body = { message: '新增成功', info: result };
    ctx.status = 200;
  }

  async updateUser() {
    const { ctx, app } = this;
    const name = ctx.request.body.name;
    const id = ctx.params.id;
    const result = await ctx.service.user.update(id, name);
    ctx.body = { message: '修改成功', info: result };
    ctx.status = 200;
  }

  // async deleteUser() {
  //   const { ctx, app } = this;
  //   const id = ctx.params.id;
  //   const result = await this.app.mysql.delete('egg_test', {
  //     id: id,
  //   });
  //   ctx.body = { id: id, message: '删除成功' };
  //   ctx.status = 200;
  // }
}
module.exports = UserController;
